package com.qsmx.store.app.main.mem;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.view.Window;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.event.MemCardTurnIcEvent;
import com.qsmx.store.app.event.MemCardTurnMemEvent;
import com.qsmx.store.app.event.MemCardTurnSuccessEvent;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.fustion.FustionTag;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.mem.entity.MemCardOrderCreatEntity;
import com.qsmx.store.app.main.mem.entity.MemManagerEntity;
import com.qsmx.store.app.main.mem.entity.MemManagerGetNewCardIcEntity;
import com.qsmx.store.app.util.CardReadUtil;
import com.qsmx.store.app.util.CountDownTimerUtil;
import com.qsmx.store.app.util.DisplayUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.app.widget.MyDialog;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.event.QrScanEvent;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.fusion.FusionString;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.dimen.DimenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class MemCardManagerTurnDelegate extends AtmosDelegate {
    private boolean isReadNow = false;
    private char mCardIcTag = 0x04;
    private char mCardNoTag = 0x3c;
    private MemManagerEntity mMemManagerOldData;
    private MemManagerGetNewCardIcEntity mMemManagerNewData;
    private String mPayMethod;
    private String mCurrentBillNo;
    private MyDialog mPayStatusDialog = null;
    private CountDownTimerUtil timer;
    private String mMemNum;

    @BindView(R2.id.tv_ic_card_num)
    AppCompatTextView tvIcCardNum;
    @BindView(R2.id.tv_mem_card_num)
    AppCompatTextView tvMemCardNum;
    @BindView(R2.id.tv_get_money)
    AppCompatTextView tvGetMoney;

    @OnClick(R2.id.tv_cash_pay)
    void onCashPay() {
        mPayMethod = "1";
        if (StringUtil.isNotEmpty(tvIcCardNum.getText().toString()) && StringUtil.isNotEmpty(tvMemCardNum.getText().toString())) {
            createOrder(mPayMethod);
        } else {
            showShortToast("请先读新卡");
        }
    }

    @OnClick(R2.id.tv_qr_pay)
    void onQrPay() {
        mPayMethod = "2";
        if (StringUtil.isNotEmpty(tvIcCardNum.getText().toString()) && StringUtil.isNotEmpty(tvMemCardNum.getText().toString())) {
            createOrder(mPayMethod);
        } else {
            showShortToast("请先读新卡");
        }
    }


    @OnClick(R2.id.iv_card_scan)
    void onCardScan() {
        if (!isReadNow) {
            CardReadUtil.StartGetCardNum(getContext(), mCardIcTag, new MemCardTurnIcEvent(new Bundle()));
            isReadNow = true;
        }
    }

    @OnClick(R2.id.iv_mem_num_scan)
    void onMemScan() {
        if (!isReadNow) {
            CardReadUtil.StartGetCardNum(getContext(), mCardNoTag, new MemCardTurnMemEvent(new Bundle()));
            isReadNow = true;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_mem_card_manager_turn;
    }

    public static MemCardManagerTurnDelegate create(MemManagerEntity memManagerData) {

        final Bundle args = new Bundle();
        args.putSerializable(FustionTag.MEM_CARD_INFO, memManagerData);

        final MemCardManagerTurnDelegate delegate = new MemCardManagerTurnDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            mMemManagerOldData = (MemManagerEntity) args.getSerializable(FustionTag.MEM_CARD_INFO);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        DisplayUtil.showMemCardTurnDisplay(getContext());

    }

    private void onGetCardInfo(String cardNum) {
        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mMachineData.getDeptId());
        params.put("icCardNo", cardNum);

        HttpHelper.RestClientGet(params, HttpUrl.MEM_GET_NEW_CARD,
                new ISuccess() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemManagerGetNewCardIcEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        mMemManagerNewData = gson.fromJson(response, type);

                        if (tvIcCardNum != null) {
                            tvIcCardNum.setText(mMemManagerNewData.getDeIcNo());
                            tvGetMoney.setText("￥" + 10);
                        } else {
                            showShortToast("空指针");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    private void createOrder(final String mPayMethod) {
        JSONObject params = new JSONObject();
        params.put("deptId", String.valueOf(FustionManager.mMachineData.getDeptId()));
        params.put("businessDate", FustionManager.mMachineData.getBusinessDate());
        params.put("shift", String.valueOf(FustionManager.mLoginData.getUser().getUser().getShift()));
        params.put("receivableMoney", "10");
        params.put("actualMoney", "10");
        params.put("changeMoney", String.valueOf(0));
        params.put("payMethod", String.valueOf(mPayMethod));
        params.put("oldMemberNo", mMemManagerOldData.getIcCard().getMemberNo());
        params.put("oldIcNo", mMemManagerOldData.getIcCard().getIcNo());
        params.put("newMemberNo", tvMemCardNum.getText().toString());
        params.put("newIcNo", tvIcCardNum.getText().toString());
        params.put("machineId", FustionManager.mMachineData.getMachineId());
        params.put("machineCode", FustionManager.mMachineData.getMachineCode());
        params.put("authorizeRecords", JSON.toJSON(new ArrayList<>()));

        HttpHelper.RestClientPostRaw(params, HttpUrl.MEM_CARD_TURN,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemCardOrderCreatEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        MemCardOrderCreatEntity mData = gson.fromJson(response, type);

                        if (mPayMethod.equals("1")) {
                            showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                        } else if (mPayMethod.equals("2")) {
                            mCurrentBillNo = mData.getSellBillNo();
                            FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                        }

                        EventBus.getDefault().post(new MemCardTurnSuccessEvent(new Bundle()));
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    private void showPayStatusDialog(String status) {

        if (mPayStatusDialog == null) {
            mPayStatusDialog = new MyDialog(getContext(), R.style.dialog);
        }
        mPayStatusDialog.setCancelable(true);
        mPayStatusDialog.show();
        Window window = mPayStatusDialog.getWindow();
        window.setContentView(R.layout.dialog_pay_status);
        int width = (int) (DimenUtil.getScreenWidth() * 0.3);
        int height = (int) (DimenUtil.getScreenHeight() * 0.3);

        window.setLayout(width, height);

        AppCompatImageView ivPayStatusImg = window.findViewById(R.id.iv_status_img);
        AppCompatTextView tvPayStatusTip = window.findViewById(R.id.tv_pay_status_tips);
        AppCompatTextView tvWaitCoinOutTime = window.findViewById(R.id.tv_wait_coin_out_time);

        if (status.equals(FustionTag.PAY_STATUS.WAIT_PAY)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_wait));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAYING)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_paying));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_SUCCESS)) {
            tvPayStatusTip.setText(getString(R.string.suit_pay_success));
            tvWaitCoinOutTime.setVisibility(View.VISIBLE);
            startCountDownTime(5, tvWaitCoinOutTime, mPayStatusDialog);
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_FAILED)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_failed));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        }

        mPayStatusDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.QrIsLoading = false;
                FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            }
        });
    }

    private void startCountDownTime(final long time, final AppCompatTextView tvWaitCoinOut, final Dialog dialog) {
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvWaitCoinOut.setText(String.format(getString(R.string.mem_card_continues_success), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                dialog.dismiss();

            }
        };
        timer.start();// 开始计时
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (event != null && event.getData() != null) {
            String qrCode = event.getData().getString(FusionString.QR_CODE);
            showShortToast(qrCode);
            qrPay(qrCode, mCurrentBillNo);

        }
    }

    private void qrPay(String qrCode, String billNo) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("authCode", qrCode);
        params.put("billNo", billNo);
        params.put("description", "");
        params.put("totalFee", "0.1");
        params.put("payBillType", "1");

        HttpHelper.RestClientPost(params, HttpUrl.CODE_PAY,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        if (code == 201) {
                            showShortToast("onSuccess:" + code + "||" + response);
                            FusionCode.QrIsLoading = false;
                            showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MemCardTurnIcEvent event) {
        if (event != null && event.getData() != null) {
            isReadNow = false;
            if (StringUtil.isNotEmpty(event.getData().getString("cardNum"))) {
                if (event.getData().getChar("tag") == mCardIcTag) {
                    onGetCardInfo(event.getData().getString("cardNum").substring(0, 18));
                }
            } else {
                showShortToast("这个卡是空的");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MemCardTurnMemEvent event) {
        if (event != null && event.getData() != null) {
            isReadNow = false;
            if (StringUtil.isNotEmpty(event.getData().getString("cardNum"))) {
                if (event.getData().getChar("tag") == mCardNoTag) {
                    mMemNum = event.getData().getString("cardNum").replaceFirst("^0*", "").substring(0, 22);
                    tvMemCardNum.setText(CardReadUtil.HexToAscii(mMemNum));
                }
            } else {
                showShortToast("这个卡是空的");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
